package com.talent.jiwen_teacher.course;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen_teacher.R;
import com.talent.jiwen_teacher.adapter.WaitSureAdapter;
import com.talent.jiwen_teacher.base.BaseFragment;
import com.talent.jiwen_teacher.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.OrderListResult;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;

import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

public class WaitSureFragment extends BaseFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;

    private List<OrderListResult.Order> dataList = new ArrayList<>();
    private WaitSureAdapter waitSureAdapter;

    public static final String REFRESH_WAIT_SURE = "refresh.wait.sure";

    private Handler handler;
    private TimeRunnable timeRunnable;
    private Thread timeThread;

    private static final int NOTIFY_TIME = 2;

    @Override
    protected void initData() {

        registEventBus();
        noDataIv.setImageResource(R.mipmap.img_not_wait_sure);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == NOTIFY_TIME){
                    waitSureAdapter.notifyData();
                }
                super.handleMessage(msg);
            }
        };
        timeRunnable = new TimeRunnable();
        timeThread = new Thread(timeRunnable);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recycleView.setLayoutManager(linearLayoutManager);
        waitSureAdapter = new WaitSureAdapter(getActivity() , dataList);
        recycleView.setAdapter(waitSureAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getOrderList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();

//        timeThread.start();

    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(REFRESH_WAIT_SURE)){
            refreshLayout.autoRefresh();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_course_list;
    }

    class TimeRunnable implements Runnable{
        boolean endThread;

        @Override
        public void run() {
            while (!endThread) {
                try {

                    Thread.sleep(1000);

                    for (OrderListResult.Order order: dataList) {

                        int time = (int)((new Date().getTime() - order.getApplyTime()) / 1000);
                        String timeFormat;
                        String min = new DecimalFormat("00").format(time / 60);
                        if (Integer.parseInt(min) < 60){
                            String mm = new DecimalFormat("00").format(time / 60);
                            String ss = new DecimalFormat("00").format(time % 60);
                            timeFormat = new String( mm + "分钟" + ss +"秒");
                        }else{
                            String hh = new DecimalFormat("00").format(time / 3600);
                            String mm = new DecimalFormat("00").format(time % 3600 / 60);
                            String ss = new DecimalFormat("00").format(time % 60);
                            timeFormat = new String( hh + "小时" + mm + "分钟" + ss + "秒");
                        }
                        order.setChangeTime(timeFormat);

                        Message msg = new Message();
                        msg.what = NOTIFY_TIME;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {

                }
            }
        }
    }
    /**
     * 获取教师待上课程
     */
    private void getOrderList() {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getTeacherApplyOrderList(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderListResult>(getActivity()) {
            @Override
            protected void _onNext(OrderListResult orderListResult) {
                dataList.clear();
                dataList.addAll(orderListResult.getOrderList());
                recycleView.getAdapter().notifyDataSetChanged();


                if(refreshLayout!=null){
                    refreshLayout.finishRefresh();
                }

                if (Validators.isEmpty(dataList)){
                    noDataIv.setVisibility(View.VISIBLE);
                }else{
                    if (!timeThread.isAlive()){
                        timeThread.start();
                    }
                    noDataIv.setVisibility(View.GONE);
                }

            }

            @Override
            protected void _onError(String message) {
                showToast(message);
                if(refreshLayout!=null){
                    refreshLayout.finishRefresh();
                }
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
    }
}
